#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ModelViewer.h"
#include "Model3D.h"
#include <QFileDialog>
#include <QMessageBox>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , glWnd(new ModelViewer)
    , model(nullptr)
{
    ui->setupUi(this);

    format.setMajorVersion(3);
    format.setMinorVersion(3);
    format.setProfile(QSurfaceFormat::CoreProfile);

    glWnd->setFormat(format);
    delete ui->centralWidget;

    ui->centralWidget = QWidget::createWindowContainer(glWnd, this);
    setCentralWidget(ui->centralWidget);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_action_Load_triggered()
{
    QString filePath = QFileDialog::getOpenFileName(this, tr("model file"));

    if (filePath.isEmpty())
        return;

    if (! model) {
        model = new Model3D(this);
        glWnd->setModel(model);
    }

    QString errMsg;

    if (! model->loadScene(filePath, errMsg))
        QMessageBox::critical(this, qAppName(), errMsg);
}

void MainWindow::on_action_aboutGL_triggered()
{
    QMessageBox::information(this, tr("OpenGL context"), glWnd->contextInformation());
}
